import { SERVER_URL } from "@/constants/Path";
import { Episode, Podcast, RecordItem } from "@/constants/types";
import { Ionicons } from "@expo/vector-icons";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect, useState } from "react";
import {
  ActivityIndicator,
  Image,
  SafeAreaView,
  ScrollView,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { saveData } from './(tabs)/index';

const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

function formatDuration(seconds: number) {
  if (seconds <= 0) {
    return "0:00";
  }
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}:${s.toString().padStart(2, "0")}`;
}


function EpisodeItem({ artwork, episode }: { artwork:string, episode: Episode }) {
  const router = useRouter();

  const handlePress = async () => {

  const newItem: RecordItem = {
    id: episode.id,
    type: "podcast",
    name: episode.name,
    duration: episode.duration,
    coverImage: artwork,
    date: new Date().toISOString().slice(0, 10),
    uri: episode.uri,
    currentTime: 0,
    mimeType: "audio/mpeg",
  };
  await saveData(newItem)
  
  router.push({
    pathname: "/player",
    params: newItem,
  });
  }
  return (
    <TouchableOpacity
      onPress={handlePress}
      style={{
        marginHorizontal: 15,
        flexDirection: "row",
        paddingVertical: 10,
        paddingHorizontal: 16,
        borderRadius: 10,
        backgroundColor: "#e0e0e0",
        marginBottom: 12,
      }}
    >
      <Image
        source={{ uri: artwork }}
        style={{
          width: 38,
          height: 38,
          borderRadius: 6,
          marginRight: 12,
          marginTop: 4,
        }}
      />
      <View style={{ flex: 1, flexDirection: "column" }}>
        <Text style={{ fontSize: 10, color: "#666", marginBottom: 2 }}>
          {formatDate(episode.date)}
        </Text>
        <Text
          style={{
            fontSize: 16,
            lineHeight: 24,
            overflow: "hidden",
            marginBottom: 2,
            fontWeight: 500,
          }}
          numberOfLines={2}
          ellipsizeMode="tail"
        >
          {episode.name || " "}
        </Text>
        <Text
          style={{
            fontSize: 12,
            color: "#666",
            lineHeight: 18,
            overflow: "hidden",
            marginBottom: 2,
          }}
          numberOfLines={2}
          ellipsizeMode="tail"
        >
          {episode.description}
        </Text>
        <Text style={{ fontSize: 12, fontWeight: 500, color: "#6e946faf" }}>
          {formatDuration(episode.duration)}
        </Text>
      </View>
    </TouchableOpacity>
  );
}


function PodcastsScreen() {
  const router = useRouter()
  const params = useLocalSearchParams() as unknown as Podcast;
  const onBack = () => {
    router.back();
  };
  
  const [episodeList, setEpisodeList] = useState<Episode[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const fetchEpisodeList = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        SERVER_URL + "/podcast/episodes?podcast_id=" + params.id
      );
      const data = await response.json();
      console.log(data)
      if(data.status === "success"){
        setEpisodeList(data.results);
      }
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    fetchEpisodeList();
  }, []);
  
  return (
    <SafeAreaView>
      {/* 顶部返回栏 */}
      <View
        style={{
          flexDirection: "row",
          alignItems: "center",
          padding: 12,
          justifyContent: "space-between",
        }}
      >
        <TouchableOpacity onPress={onBack} style={{ padding: 6 }}>
          <Ionicons name="chevron-back" size={26} color="#333" />
        </TouchableOpacity>
      </View>
      {/* 主内容区域 */}
      <ScrollView contentContainerStyle={{ paddingBottom: 120 }}>
        {/* 播客信息区 */}
        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            padding: 15,
          }}
        >
          <Image
            source={{ uri: params.artwork }}
            style={{
              width: 80,
              height: 80,
              borderRadius: 8,
              marginRight: 22,
            }}
          />
          <View
            style={{
              flex: 1,
            }}
          >
            <Text
              style={{
                fontSize: 22,
                marginBottom: 6,
              }}
            >
              {params.name}
            </Text>
            <Text
              style={{
                fontSize: 14,
                color: "#666",
              }}
            >
              {params.artist}
            </Text>
          </View>
        </View>
        {/* 加载 */}
        {loading && <ActivityIndicator />}
        {/* 播客描述 */}
        {!loading && (
          <>
            <View
              style={{ marginHorizontal: 15, marginTop: 10, marginBottom: 20 }}
            >
              <Text
                style={{
                  fontSize: 14,
                  color: "#999",
                }}
              >
                共{params.count}集
              </Text>
            </View>
            {episodeList.map((episode) => (
              <EpisodeItem
                artwork={params.artwork}
                episode={episode}
                key={episode.id}
              />
            ))}
            <Text style={{ fontSize: 14, color: "#999", textAlign: "center" }}>
              更多
            </Text>
          </>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

export default PodcastsScreen;